<?php
namespace app\api\controller;
use think\Controller;
use think\Db;
use lib\Curl;
class Meta extends Base{
    private function tokensq(){
        $timestamp=time();
        $header = array("Content-type:application/json;","Accept:application/json","Accept-Version:1.0");
        $url = "https://api.matedata.net/security/access-token?timestamp=".$timestamp."&appId=7fbb4c62d64d4735b62f37dc9f1d0485&accessKey=".md5('6c385b540b6446cba1fa48920e70a41e:'.$timestamp);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,0);
        curl_setopt($ch, CURLOPT_POST, false);
        curl_setopt($ch, CURLOPT_HTTPHEADER,$header);
        $data = curl_exec($ch);
        curl_close($ch);
        $data = json_decode($data,true);
        return $data['resData']['accessToken'];
    }
    private function tokenyys(){
        $timestamp=time();
        $header = array("Content-type:application/json;","Accept:application/json","Accept-Version:1.0");
        $url = "https://api.matedata.net/security/access-token?timestamp=".$timestamp."&appId=8f8f05f6e57540bb867061c96ac40069&accessKey=".md5('6c385b540b6446cba1fa48920e70a41e:'.$timestamp);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,0);
        curl_setopt($ch, CURLOPT_POST, false);
        curl_setopt($ch, CURLOPT_HTTPHEADER,$header);
        $data = curl_exec($ch);
        curl_close($ch);
        $data = json_decode($data,true);
        return $data['resData']['accessToken'];
    }
    private function tokentj(){
        $timestamp=time();
        $header = array("Content-type:application/json;","Accept:application/json","Accept-Version:1.0");
        $url = "https://api.matedata.net/security/access-token?timestamp=".$timestamp."&appId=c7b99d46109c4ac7b6b24f5f369c7360&accessKey=".md5('6c385b540b6446cba1fa48920e70a41e:'.$timestamp);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,0);
        curl_setopt($ch, CURLOPT_POST, false);
        curl_setopt($ch, CURLOPT_HTTPHEADER,$header);
        $data = curl_exec($ch);
        curl_close($ch);
        $data = json_decode($data,true);
        return $data['resData']['accessToken'];
    }
    private function tokenzm(){
        $timestamp=time();
        $header = array("Content-type:application/json;","Accept:application/json","Accept-Version:1.0");
        $url = "https://api.matedata.net/security/access-token?timestamp=".$timestamp."&appId=cd946c5d865243df8baac4ce76e69e12&accessKey=".md5('6c385b540b6446cba1fa48920e70a41e:'.$timestamp);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,0);
        curl_setopt($ch, CURLOPT_POST, false);
        curl_setopt($ch, CURLOPT_HTTPHEADER,$header);
        $data = curl_exec($ch);
        curl_close($ch);
        $data = json_decode($data,true);
        return $data['resData']['accessToken'];
    }
    private function tokenzmq(){
        $timestamp=time();
        $header = array("Content-type:application/json;","Accept:application/json","Accept-Version:1.0");
        $url = "https://api.matedata.net/security/access-token?timestamp=".$timestamp."&appId=32fcc70cdf5f4167812e56ae5a85921a&accessKey=".md5('6c385b540b6446cba1fa48920e70a41e:'.$timestamp);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,0);
        curl_setopt($ch, CURLOPT_POST, false);
        curl_setopt($ch, CURLOPT_HTTPHEADER,$header);
        $data = curl_exec($ch);
        curl_close($ch);
        $data = json_decode($data,true);
        return $data['resData']['accessToken'];
    }
    private function curlPost($url, $post_data, $json, $token){
        $ch=curl_init();
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT,10);
        curl_setopt($ch, CURLOPT_TIMEOUT,10);
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch, CURLOPT_POST,1);
        if($json){
          curl_setopt($ch,CURLOPT_HTTPHEADER,array("Content-Type: application/json; charset=utf-8","Accept-Version:1.0","Access-Token:{$token}"));
        }
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        $output = curl_exec($ch);
        curl_close($ch);
        $output_array = json_decode($output, true);
        return $output_array;
    }
    //运营商授权
    public function yysarg(){
        if(!empty(input("param.token"))){
            $token=input("param.token");
            $id=$this->do_mdecrypt($token);
            $user=Db::name('users')->where('id', $id)->find();
        }else{
            return json(['code' => 501, 'msg' => '令牌呢？']);exit();
        }
        Db::name('users')->where('id', $id)->update(['yys_state' => 0]);
        $result=$this->tokensq();
        $orderNo=date('YmdHis').mt_rand(1000,9999);
        $iframeurl = "https://api.matedata.net/dx/yys?accessToken=".$result."&orderNo=".$orderNo."&name=".$user['name']."&idNo=".$user['idcard']."&phone=".$user['phone']."&backUrl=http://www.kbb123.com/api/meta/bnotifyUrls&onLoginDone=0&dataUrl=http://www.kbb123.com/api/meta/notifyUrls";
        return json(['code' => 200, 'msg' => '成功','iframeurl'=>$iframeurl]);exit();
    }
    public function bnotifyUrls(){
        $rel1=file_get_contents('php://input');
        $data=json_decode($rel1);
        return $data;
    }
    //运营商授权回调通知
    public function notifyUrls(){
        $rel1=file_get_contents('php://input');
        $data=json_decode($rel1);
        if ($data->result==1) {
            Db::name('users')->where('phone', $data->phone)->update(['task_id' => $data->taskId,'yys_orderno' => $data->orderNo,'yys_state' => 1]);
        }elseif($data->result==0){
            Db::name('users')->where('phone', $data->phone)->update(['task_id' => $data->taskId,'yys_orderno' => $data->orderNo,'yys_state' => 0]);
        }
    }
    //运营商报告
    public function yysreport(){
        $user_id = input('user_id');
        $result=$this->tokenyys();
        $users=Db::name('users')->where('id',$user_id)->find();
        Db::name('users')->where('id',$user_id)->update(['yystime' =>time()]);
        $timestamp=time();
        $taskId=$users['task_id'];
        $phone=$users['phone'];
        $payloads='{"phone":"'.$phone.'","taskId":"'.$taskId.'","timestamp":'.$timestamp.'}';
        $sign=hash_hmac('sha256',$payloads,'6c385b540b6446cba1fa48920e70a41e');
        $param = '{"timestamp":'.$timestamp.',"sign":"'.$sign.'","payload":{"taskId": "'.$taskId.'","phone": "'.$phone.'"}}';
        $results = $this->curlPost("https://api.matedata.net/dx/yys-report",$param,1,$result);
        $results=json_encode($results,true);
        return $results;
    }
    public function yysState(){
        if(!empty(input("param.token"))){
            $token=input("param.token");
        }else{
            return json(['code' => 501, 'msg' => '令牌呢？']);exit();
        }
        $id=$this->do_mdecrypt($token);
        $result=Db::name('users')->where('id', $id)->find();
        if($result['yys_state']>=1){
            return json(['code' => 200, 'msg' => '成功']);exit();
        }else{
            return json(['code' => 201, 'msg' => '正在进行时...']);exit();
        }
    }
    public function allday(){
        $user_id = input('user_id');
        $result=$this->tokentj();
        $userinfo = Db::name('users')->where('id',$user_id)->find();
        $phone=$userinfo['phone'];
        $timestamp=time();
        $payloads='{"idNo":"'.$userinfo['idcard'].'","name":"'.$userinfo['name'].'","phone":"'.$phone.'","timestamp":'.$timestamp.'}';
        $sign=hash_hmac("sha256",$payloads,"6c385b540b6446cba1fa48920e70a41e");
        $param = '{"timestamp":'.$timestamp.',"sign":"'.$sign.'","payload":{"name": "'.$userinfo['name'].'","idNo": "'.$userinfo['idcard'].'","phone": "'.$phone.'"}}';
        $results = $this->curlPost("https://api.matedata.net/credit/hologram",$param,1,$result);
        $results=json_encode($results,true);
        return $results;
    }
    public function sesameState(){
        if(!empty(input("param.token"))){
            $token=input("param.token");
        }else{
            return json(['code' => 501, 'msg' => '令牌呢？']);exit();
        }
        $user_id=$this->do_mdecrypt($token);
        $userinfo = Db::name('users')->where('id',$user_id)->find();
        if($userinfo['sesame_state']==1){
            return json(['code' => 200, 'msg' => '已授权','score'=>$userinfo['sesame_score']]);exit();
        }else{
            return json(['code' => 500, 'msg' => '未授权']);exit();
        }
    }
    public function sesame(){
        if(!empty(input("param.token"))){
            $token=input("param.token");
        }else{
            return json(['code' => 501, 'msg' => '令牌呢？']);exit();
        }
        $user_id=$this->do_mdecrypt($token);
        $result=$this->tokenzm();
        $userinfo = Db::name('users')->where('id',$user_id)->find();
        if($userinfo['sesame_state']==1){
            return json(['code' => 200, 'msg' => '已授权','score'=>$userinfo['sesame_score']]);exit();
        }
        $phone=$userinfo['phone'];
        $timestamp=time();
        $notifyUrl='http://'.$_SERVER['HTTP_HOST'].'/api/meta/zmnotifyUrls';
        $payloads='{"idNo":"'.$userinfo['idcard'].'","mobile":"'.$phone.'","name":"'.$userinfo['name'].'","notifyUrl":"'.$notifyUrl.'","timestamp":'.$timestamp.'}';
        $sign=hash_hmac("sha256",$payloads,"6c385b540b6446cba1fa48920e70a41e");
        $param = '{"timestamp":'.$timestamp.',"sign":"'.$sign.'","payload":{"name": "'.$userinfo['name'].'","idNo": "'.$userinfo['idcard'].'","mobile": "'.$phone.'","notifyUrl":"'.$notifyUrl.'"}}';
        $results=$this->curlPost("https://api.matedata.net/credit/zmf/h5v1/auth",$param,1,$result);
        $results=json_encode($results,true);
        $resultt=json_decode($results);
        if($resultt->resData->success=='false'){
            return json(['code' => 502, 'msg' => '要授权','url' =>$resultt->resData->authUrl]);exit();
        }elseif($resultt->resData->success=='true'){
            Db::name('users')->where('id',$user_id)->update(['sesame_state'=>1]);
            $zmfUrl='http://'.$_SERVER['HTTP_HOST'].'/api/meta/zmfQuery';
            $zmfUrlp['user_id']=$user_id;
            $zmfQuery=Curl::http_curl($zmfUrl,$zmfUrlp);
            return json(['code' => 201, 'msg' => '已授权','score'=>$userinfo['sesame_score']]);exit();
        }
        return json(['code' => 500, 'msg' => '第三方错误']);exit();
    }
    //芝麻授权回调通知
    public function zmnotifyUrls(){
        $rel1=file_get_contents('php://input');
        Db::name('test')->where('id',1)->update(['test'=>$rel1]);
    }
    public function zmfQuery(){
        $user_id = input('user_id');
        $result=$this->tokenzm();//32fcc70cdf5f4167812e56ae5a85921a
        $userinfo = Db::name('users')->where('id',$user_id)->find();
        $phone=$userinfo['phone'];
        $timestamp=time();
        $payloads='{"idNo":"'.$userinfo['idcard'].'","mobile":"'.$phone.'","name":"'.$userinfo['name'].'","timestamp":'.$timestamp.'}';
        $sign=hash_hmac("sha256",$payloads,"6c385b540b6446cba1fa48920e70a41e");
        $param = '{"timestamp":'.$timestamp.',"sign":"'.$sign.'","payload":{"name": "'.$userinfo['name'].'","idNo": "'.$userinfo['idcard'].'","mobile": "'.$phone.'"}}';
        $results=$this->curlPost("https://api.matedata.net/credit/zmf/h5v1/query",$param,1,$result);
        $results=json_encode($results,true);
        $resultt=json_decode($results);
        if($resultt->resData->score){
            Db::name('users')->where('id',$user_id)->update(['sesame_score'=>$resultt->resData->score]);
            return $resultt->resData->score;
        }
    }
    //解密
    private function do_mdecrypt($string, $key=''){
        $key= !empty($key) ? $key : config('byzk.KEY');
        $operation = 'D';
        $key=md5($key); 
        $key_length=strlen($key); 
        $string=$operation=='D'?base64_decode($string):substr(md5($string.$key),0,8).$string; 
        $string_length=strlen($string); 
        $rndkey=$box=array(); 
        $result=''; 
        for($i=0;$i<=255;$i++){ 
            $rndkey[$i]=ord($key[$i%$key_length]); 
            $box[$i]=$i; 
        } 
        for($j=$i=0;$i<256;$i++){ 
            $j=($j+$box[$i]+$rndkey[$i])%256; 
            $tmp=$box[$i]; 
            $box[$i]=$box[$j]; 
            $box[$j]=$tmp; 
        } 
        for($a=$j=$i=0;$i<$string_length;$i++){ 
            $a=($a+1)%256; 
            $j=($j+$box[$a])%256; 
            $tmp=$box[$a]; 
            $box[$a]=$box[$j]; 
            $box[$j]=$tmp; 
            $result.=chr(ord($string[$i])^($box[($box[$a]+$box[$j])%256])); 
        } 
        if($operation=='D'){ 
            if(substr($result,0,8)==substr(md5(substr($result,8).$key),0,8)){ 
                return substr($result,8); 
            }else{ 
                return''; 
            } 
        }else{ 
            return str_replace('=','',base64_encode($result)); 
        } 
    }
}